const db = require("../db/index.js");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const jswConfig = require("../jwt_config/index.js");

exports.register = (req, res) => {
  const body = req.body;
  if (!body.account || !body.password || !body.email) {
    return res.send({
      msg: "账号/密码/email不能为空",
      code: 1,
    });
  }
  const sql = "select * from users where account=?";
  db.query(sql, body.account, (err, results) => {
    if (err) {
      return res.cc(err);
    }
    if (results && results.length > 0) {
      return res.cc("账号已经存在");
    }
    const password = bcrypt.hashSync(body.password, 16);
    const insetSql = "insert into users set ?";
    db.query(
      insetSql,
      {
        account: body.account,
        password: password,
        identity: "普通用户",
        create_time: new Date(),
        email: body.email,
        status: 0,
      },
      (err, results) => {
        if (err) {
          return res.cc(err);
        }
        if (results && results.affectedRows != 1) {
          return res.send({
            msg: "注册账号失败,请稍后重试",
            code: 1,
          });
        }
        db.query("select * from users where account=?", body.account, (err, result) => {
          if (err) return res.cc(err);
          res.send(createLoginResult(result[0], "注册成功"));
        });
      }
    );
  });
};

exports.login = (req, res) => {
  const loginInfo = req.body;
  const sql = "select * from users where account= ?";
  db.query(sql, loginInfo.account, (err, result) => {
    if (err) return res.cc(err);
    if (result.length != 1) {
      return res.cc("登录失败 " + result.length);
    }
    const compareResult = bcrypt.compareSync(loginInfo.password, result[0].password);
    if (!compareResult) {
      return res.cc("登录失败,密码不正确");
    }
    if (result[0].status == 1) {
      return res.cc("账号被冻结");
    }
    res.send(createLoginResult(result[0], "登录成功"));
  });
};

function createLoginResult(result, msg) {
  const user = {
    ...result,
  };
  const tokenStr = jwt.sign(user, jswConfig.jwtSecretKey, {
    expiresIn: "12h",
  });
  return {
    data: {
      ...user,
      password: "",
    },
    msg: msg,
    code: 0,
    token: "Bearer_" + tokenStr,
  };
}

exports.verifyAccount = (req, res) => {
  const { account, email } = req.body;
  const sql = "select email from users where account = ?";
  db.query(sql, account, (err, result) => {
    if (err) return res.cc(err);
    if (!result) return res.cc("该账号不存在");
    if (result.length > 1) {
      return res.cc("该账号异常");
    }
    if (result[0].email != email) {
      return res.cc("邮箱不匹配");
    }
    res.send({
      code: 0,
      message: "该账号可用",
      data: {
        account,
        email,
      },
    });
  });
};
